package org.glickr.api.people

import org.glickr.api.FlickrApiMethod
import org.glickr.FlickrPeople
import groovy.util.slurpersupport.GPathResult
import org.glickr.FlickrPhotoSet
import org.glickr.FlickrPhoto
import org.glickr.FlickrServicePluginException
import org.glickr.FlickrServiceApiException

/* ----------------------------------------------------------------------------------------------------
REQUEST: flickr.people.getPublicPhotos
INFO: Get a list of public photos for the given user.

AUTHENTICATION: This method does not require authentication.

ARGUMENTS:
api_key (Required): Your API application key.
user_id (Required): The NSID of the user who's photos to return.
safe_search (Optional): Safe search setting:
-1 for safe.
-2 for moderate.
-3 for restricted.
(Please note: Un-authed calls can only see Safe content.)
extras (Optional): A comma-delimited list of extra information to fetch for each returned record. Currently supported fields are: description, license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo, tags, machine_tags, o_dims, views, media, path_alias, url_sq, url_t, url_s, url_q, url_m, url_n, url_z, url_c, url_l, url_o
per_page (Optional): Number of photos to return per page. If this argument is omitted, it defaults to 100. The maximum allowed value is 500.
page (Optional): The page of results to return. If this argument is omitted, it defaults to 1.

EXAMPLE RESPONSE:

This method returns the standard photo list xml:
<photos page="2" pages="89" perpage="10" total="881">
	<photo id="2636" owner="47058503995@N01"
		secret="a123456" server="2" title="test_04"
		ispublic="1" isfriend="0" isfamily="0" />
	<photo id="2635" owner="47058503995@N01"
		secret="b123456" server="2" title="test_03"
		ispublic="0" isfriend="1" isfamily="1" />
	<photo id="2633" owner="47058503995@N01"
		secret="c123456" server="2" title="test_01"
		ispublic="1" isfriend="0" isfamily="0" />
	<photo id="2610" owner="12037949754@N01"
		secret="d123456" server="2" title="00_tall"
		ispublic="1" isfriend="0" isfamily="0" />
</photos>
To map <photo> elements to urls, please read the url documentation.
---------------------------------------------------------------------------------------------------- */


class peopleGetPublicPhotos implements FlickrApiMethod {
    //
    //  API METHOD
    //
    static final String apiMethod = 'flickr.people.getPublicPhotos'

    //
    //  VALIDATOR
    //
    def validatorClosure = { FlickrPeople people ->
        if (!people || !people?.nsid) { return [validated:false, message:"Required value 'FlickrPeople.nsid' is missing"] }
        return [validated:true]
    }

    //
    //  PARAMS
    //
    def paramsClosure = { FlickrPeople people ->
        // todo implement
        [   user_id:people?.nsid,
//            tags:params.tags,
//            text:params.text,
//            page:params.page,
//            per_page:params.perPage,
            extras:'url_t'  // todo merge extra's but always have url_t since we use this for parsing the farmId from
        ]

    }

    //
    //  PROCESSOR
    //
    Closure processorClosure = { GPathResult response, FlickrPeople people ->

        FlickrPhotoSet photoSet = new FlickrPhotoSet()
        // photoSet.params = params

        photoSet.page = response.photos.@page.toInteger()
        photoSet.pages = response.photos.@pages.toInteger()
        photoSet.perPage = response.photos.@perpage.toInteger()
        photoSet.total = response.photos.@total.toInteger()

        response.photos.children().findAll{ it.name() == 'photo' }.each {
            FlickrPhoto photo = new FlickrPhoto()

            // description, license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo, tags, machine_tags, o_dims, views, media, path_alias, url_sq, url_t, url_s, url_q, url_m, url_n, url_z, url_c, url_l, url_o

            photo.id = it.@id.toLong()
            // photo.owner = it.@owner.toLong()
            photo.secret = it.@secret.toString()
            photo.serverId = it.@server.toInteger()
            photo.title = it.@title.toString()
            photo.isPublic = (it.@ispublic?.toString() == '1')
            photo.isFriend = (it.@isfriend?.toString() == '1')
            photo.isFamily = (it.@isfamily?.toString() == '1')

            // parse farmId from thumbnail url
            def farm = it.@url_t.toString().find(/http:\/\/farm[0-9]+\..*flickr\.com/)?.find(/[0-9]+/)
            if (farm) {
                photo.farmId = Integer.parseInt(farm)
            }
            photoSet.photos.add(photo)
        }
        return photoSet
    }

    //
    //  ERROR CODES
    //
    Closure errorsClosure = { GPathResult response ->
        if (response.err.@code.toInteger() == 1) { return null }      // user not found

        // recoverable errors
        if ([100,105,116].contains(response.err.@code.toInteger())) {
            return new FlickrServiceApiException(response)
        } else {
            return new FlickrServicePluginException(response)
        }
    }
}
